{% load static %}
<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{% block title %}固定资产管理系统{% endblock %}</title>

    <!-- PWA Meta Tags -->
    <meta name="theme-color" content="#4A90E2">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="default">
    <meta name="apple-mobile-web-app-title" content="资产管理">
    <meta name="description" content="企业固定资产全生命周期管理系统">

    <!-- PWA Icons -->
    <link rel="apple-touch-icon" href="/static/images/icon-192x192.png">
    <link rel="icon" type="image/png" sizes="192x192" href="/static/images/icon-192x192.png">

    <!-- Favicon -->
    <link rel="icon" type="image/svg+xml" href="{% static 'favicon.svg' %}">
    <link rel="alternate icon" href="{% static 'favicon.svg' %}">
    
    <!-- PWA Manifest -->
    <link rel="manifest" href="{% static 'manifest.json' %}">
    
    <!-- Local CSS Files -->
    <link href="{% static 'vendor/bootstrap/bootstrap.min.css' %}" rel="stylesheet">
    <link href="{% static 'vendor/fontawesome/all.min.css' %}" rel="stylesheet">
    <link href="{% static 'css/list-actions.css' %}" rel="stylesheet">
    
    <!-- CDN Fallback for ECharts -->
    <script src="https://cdn.jsdelivr.net/npm/echarts@5.4.0/dist/echarts.min.js" onerror="console.warn('ECharts CDN failed to load')"></script>
    <style>
        .navbar-brand {
            font-weight: bold;
        }

        .card {
            transition: transform 0.2s;
            margin-bottom: 20px;
        }

        .card:hover {
            transform: translateY(-5px);
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
        }

        .footer {
            margin-top: 50px;
            padding: 20px 0;
            border-top: 1px solid #eee;
            text-align: center;
            color: #666;
        }

        .feature-icon {
            font-size: 2rem;
            margin-bottom: 15px;
        }

        /* 自定义导航栏颜色 */
        .navbar-custom {
            background: linear-gradient(135deg, #1A2C5B 0%, #2A407A 100%);
        }

        /* 下拉菜单样式优化 */
        .dropdown-menu-center {
            min-width: auto;
            width: auto;
            border-radius: 12px;
            box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
            border: none;
            padding: 8px 0;
        }

        .dropdown-header {
            color: #495057 !important;
            font-weight: 600;
            font-size: 0.85rem;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            padding: 8px 20px 4px 20px;
            margin-bottom: 4px;
        }

        .dropdown-item {
            padding: 8px 20px;
            font-size: 0.9rem;
            transition: all 0.2s ease;
            border-radius: 0;
        }

        .dropdown-item:hover {
            background: linear-gradient(135deg, #4A90E2 0%, #63B8FF 100%);
            color: white;
            transform: translateX(3px);
        }

        .dropdown-item i {
            width: 16px;
            text-align: center;
            margin-right: 8px;
        }

        .dropdown-divider {
            margin: 8px 16px;
            border-color: #e9ecef;
        }

        /* 下拉菜单优化样式 */
        .dropdown-menu {
            border: none;
            border-radius: 8px;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
            padding: 8px 0;
            margin-top: 4px;
            min-width: 180px;
        }

        /* 下拉菜单项优化 - 简化版本 */
        .dropdown-item {
            padding: 10px 16px;
            font-size: 0.9rem;
            transition: all 0.15s ease;
            border-radius: 4px;
            margin: 2px 8px;
        }

        .dropdown-item:hover,
        .dropdown-item:focus {
            background: linear-gradient(135deg, #4A90E2 0%, #63B8FF 100%);
            color: white;
        }

        .dropdown-item i {
            width: 18px;
            text-align: center;
            margin-right: 8px;
        }

        /* 分割线优化 */
        .dropdown-divider {
            margin: 8px 16px;
            border-color: #e9ecef;
        }

        /* 移动端优化 */
        @media (max-width: 768px) {
            .dropdown-menu {
                min-width: 160px;
                font-size: 0.85rem;
            }

            .dropdown-item {
                padding: 8px 12px;
            }
        }

        /* 全局：当需要居中时给 toast 容器添加该类 */
        #toastContainer.center-top {
            top: 20px !important;
            right: auto !important;
            left: 50% !important;
            transform: translateX(-50%);
        }
        /* 居中时稍微放大宽度便于阅读长信息 */
        #toastContainer.center-top .toast { min-width: 420px; }
        @media (max-width: 576px) {
            #toastContainer.center-top .toast { min-width: 300px; }
        }

        /* Toast 内容可换行且可滚动，避免遮挡 */
        #toastContainer .toast .toast-body {
            white-space: pre-wrap;
            max-height: 240px;
            overflow: auto;
        }
    </style>
    {% block ui_flags %}
    <script>
        // 页面可通过覆盖本 block 修改默认行为
        window.UI_FLAGS = {
            toastCenter: true,              // 是否将Toast置于顶部居中
            successModalOnSuccess: true     // 是否在存在成功消息时弹出成功模态框
        };
    </script>
    {% endblock %}
    {% block extra_css %}{% endblock %}
</head>

<body>
    <nav class="navbar navbar-expand-lg navbar-dark navbar-custom">
        <div class="container-fluid">
            <a class="navbar-brand" href="{% url 'assets:index' %}">固定资产管理系统</a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav">
                    {% if user.is_authenticated %}
                    <li class="nav-item">
                        <a class="nav-link" href="{% url 'assets:dashboard' %}">仪表板</a>
                    </li>
                    {% if user.is_staff %}
                    <li class="nav-item dropdown">
                        <a class="nav-link dropdown-toggle" href="#" id="systemManagementDropdown" role="button"
                            data-bs-toggle="dropdown">
                            <i class="fas fa-cogs"></i> 系统管理
                        </a>
                        <ul class="dropdown-menu dropdown-menu-center">
                            <li>
                                <h6 class="dropdown-header"><i class="fas fa-users me-2"></i>用户管理</h6>
                            </li>
                            <li><a class="dropdown-item" href="{% url 'assets:user_list' %}"><i
                                        class="fas fa-users me-2"></i>用户管理</a></li>
                            <li><a class="dropdown-item" href="{% url 'assets:group_list' %}"><i
                                        class="fas fa-users-cog me-2"></i>用户组管理</a></li>

                            <li>
                                <hr class="dropdown-divider">
                            </li>

                            <li>
                                <h6 class="dropdown-header"><i class="fas fa-clipboard-list me-2"></i>日志管理</h6>
                            </li>
                            <li><a class="dropdown-item" href="{% url 'assets:system_log_list' %}"><i
                                        class="fas fa-server me-2"></i>系统日志</a></li>
                            <li><a class="dropdown-item" href="{% url 'assets:asset_log_list' %}"><i
                                        class="fas fa-history me-2"></i>操作日志</a></li>

                            <li>
                                <hr class="dropdown-divider">
                            </li>

                            <li>
                                <h6 class="dropdown-header"><i class="fas fa-tools me-2"></i>系统工具</h6>
                            </li>
                            <li><a class="dropdown-item" href="{% url 'assets:system_parameter_list' %}"><i
                                        class="fas fa-sliders-h me-2"></i>系统参数</a></li>
                            <li><a class="dropdown-item" href="{% url 'assets:notification_list' %}"><i
                                        class="fas fa-bell me-2"></i>通知管理</a></li>
                            <li><a class="dropdown-item" href="{% url 'assets:data_backup_list' %}"><i
                                        class="fas fa-database me-2"></i>数据备份</a></li>
                        </ul>
                    </li>
                    {% endif %}
                    <li class="nav-item dropdown">
                        <a class="nav-link dropdown-toggle" href="#" id="orgManagementDropdown" role="button"
                            data-bs-toggle="dropdown">
                            <i class="fas fa-sitemap"></i> 组织架构
                        </a>
                        <ul class="dropdown-menu dropdown-menu-center">
                            <li><a class="dropdown-item" href="{% url 'assets:organization_list' %}"><i
                                        class="fas fa-building me-2"></i>组织管理</a></li>
                            <li><a class="dropdown-item" href="{% url 'assets:department_list' %}"><i
                                        class="fas fa-sitemap me-2"></i>部门管理</a></li>
                            <li><a class="dropdown-item" href="{% url 'assets:location_list' %}"><i
                                        class="fas fa-map-marker-alt me-2"></i>位置管理</a></li>
                        </ul>
                    </li>
                    <li class="nav-item dropdown">
                        <a class="nav-link dropdown-toggle" href="#" id="assetManagementDropdown" role="button"
                            data-bs-toggle="dropdown">
                            <i class="fas fa-boxes"></i> 资产管理
                        </a>
                        <ul class="dropdown-menu dropdown-menu-center">
                            <li><a class="dropdown-item" href="{% url 'assets:category_list' %}"><i
                                        class="fas fa-tags me-2"></i>资产类别</a></li>
                            <li><a class="dropdown-item" href="{% url 'assets:asset_list' %}"><i
                                        class="fas fa-boxes me-2"></i>资产列表</a></li>
                            <li>
                                <hr class="dropdown-divider">
                            </li>
                            <!-- 资产管理增强功能 -->
                            <li>
                                <h6 class="dropdown-header"><i class="fas fa-magic me-2"></i>增强功能</h6>
                            </li>
                            <li><a class="dropdown-item" href="{% url 'assets:asset_scan_qr' %}"><i
                                        class="fas fa-qrcode me-2"></i>扫描二维码</a></li>
                            <li><a class="dropdown-item" href="{% url 'assets:label_template_list' %}"><i
                                        class="fas fa-tags me-2"></i>标签模板管理</a></li>
                            <li>
                                <hr class="dropdown-divider">
                            </li>
                            <li><a class="dropdown-item" href="{% url 'assets:maintenance_list' %}"><i
                                        class="fas fa-tools me-2"></i>维修管理</a></li>
                            <li><a class="dropdown-item" href="{% url 'assets:depreciation_report' %}"><i
                                        class="fas fa-chart-line me-2"></i>折旧管理</a></li>
                            <li>
                                <hr class="dropdown-divider">
                            </li>
                            <li><a class="dropdown-item" href="{% url 'assets:inventory_plan_list' %}"><i
                                        class="fas fa-clipboard-list me-2"></i>盘点计划</a></li>
                            <li><a class="dropdown-item" href="{% url 'assets:inventory_plan_create' %}"><i
                                        class="fas fa-plus-circle me-2"></i>创建盘点</a></li>
                            <li>
                                <hr class="dropdown-divider">
                            </li>
                            <li><a class="dropdown-item" href="{% url 'assets:borrow_request_list' %}"><i
                                        class="fas fa-handshake me-2"></i>借用管理</a></li>
                            <li><a class="dropdown-item" href="{% url 'assets:borrow_request_create' %}"><i
                                        class="fas fa-plus me-2"></i>申请借用</a></li>
                            <li><a class="dropdown-item" href="{% url 'assets:overdue_borrows' %}"><i
                                        class="fas fa-exclamation-triangle me-2"></i>逾期提醒</a></li>
                            <li>
                                <hr class="dropdown-divider">
                            </li>
                            <li><a class="dropdown-item" href="{% url 'assets:supplier_list' %}"><i
                                        class="fas fa-truck me-2"></i>供应商管理</a></li>
                            <li><a class="dropdown-item" href="{% url 'assets:contract_list' %}"><i
                                        class="fas fa-file-contract me-2"></i>合同管理</a></li>
                            <li>
                                <hr class="dropdown-divider">
                            </li>
                            <li>
                                <h6 class="dropdown-header"><i class="fas fa-laptop-code me-2"></i>软件管理</h6>
                            </li>
                            <li><a class="dropdown-item" href="{% url 'assets:software_list' %}"><i
                                        class="fas fa-laptop-code me-2"></i>软件列表</a></li>
                            <li><a class="dropdown-item" href="{% url 'assets:license_list' %}"><i
                                        class="fas fa-key me-2"></i>许可管理</a></li>
                        </ul>
                    </li>
                    <li class="nav-item dropdown">
                        <a class="nav-link dropdown-toggle" href="#" id="inventoryManagementDropdown" role="button"
                            data-bs-toggle="dropdown">
                            <i class="fas fa-warehouse"></i> 库存管理
                        </a>
                        <ul class="dropdown-menu dropdown-menu-center">
                            <li><a class="dropdown-item" href="{% url 'assets:warehouse_list' %}"><i
                                        class="fas fa-warehouse me-2"></i>仓库管理</a></li>
                            <li><a class="dropdown-item" href="{% url 'assets:consumable_list' %}"><i
                                        class="fas fa-box me-2"></i>耗材管理</a></li>
                            <li><a class="dropdown-item" href="{% url 'assets:inventory_log_list' %}"><i
                                        class="fas fa-history me-2"></i>库存记录</a></li>
                        </ul>
                    </li>
                    <!-- Feature disabled: AI智能化 导航入口暂时隐藏
                    <li class="nav-item dropdown">
                        <a class="nav-link dropdown-toggle" href="#" id="aiManagementDropdown" role="button"
                            data-bs-toggle="dropdown">
                            <i class="fas fa-brain"></i> AI智能化
                        </a>
                        <ul class="dropdown-menu dropdown-menu-center">
                            <li>
                                <h6 class="dropdown-header"><i class="fas fa-brain me-2"></i>智能分析</h6>
                            </li>
                            <li><a class="dropdown-item" href="{% url 'assets:ai_dashboard' %}"><i
                                        class="fas fa-tachometer-alt me-2"></i>AI仪表板</a></li>
                            <li><a class="dropdown-item" href="{% url 'assets:ai_recommendations_list' %}"><i
                                        class="fas fa-lightbulb me-2"></i>智能推荐</a></li>
                            <li><a class="dropdown-item" href="{% url 'assets:ai_anomaly_detection_list' %}"><i
                                        class="fas fa-exclamation-triangle me-2"></i>异常检测</a></li>
                            <li><a class="dropdown-item" href="{% url 'assets:ai_predictive_maintenance' %}"><i
                                        class="fas fa-tools me-2"></i>预测性维护</a></li>
                            <li>
                                <hr class="dropdown-divider">
                            </li>
                            <li><a class="dropdown-item" href="{% url 'assets:ai_analytics' %}"><i
                                        class="fas fa-chart-bar me-2"></i>AI分析统计</a></li>
                        </ul>
                    </li>
                    -->
                    <!-- Feature disabled: 高级搜索 导航入口暂时隐藏
                    <li class="nav-item dropdown">
                        <a class="nav-link dropdown-toggle" href="#" id="searchManagementDropdown" role="button"
                            data-bs-toggle="dropdown">
                            <i class="fas fa-search-plus"></i> 高级搜索
                        </a>
                        <ul class="dropdown-menu dropdown-menu-center">
                            <li>
                                <h6 class="dropdown-header"><i class="fas fa-search me-2"></i>搜索功能</h6>
                            </li>
                            <li><a class="dropdown-item" href="{% url 'assets:advanced_search' %}"><i
                                        class="fas fa-search-plus me-2"></i>高级搜索</a></li>
                            <li><a class="dropdown-item" href="{% url 'assets:search_templates' %}"><i
                                        class="fas fa-save me-2"></i>搜索模板</a></li>
                            <li>
                                <hr class="dropdown-divider">
                            </li>
                            <li>
                                <h6 class="dropdown-header"><i class="fas fa-bolt me-2"></i>快速搜索</h6>
                            </li>
                            <li><a class="dropdown-item" href="{% url 'assets:asset_list' %}?quick_search=idle"><i
                                        class="fas fa-pause me-2"></i>闲置资产</a></li>
                            <li><a class="dropdown-item" href="{% url 'assets:asset_list' %}?quick_search=maintenance"><i
                                        class="fas fa-tools me-2"></i>维修中资产</a></li>
                            <li><a class="dropdown-item" href="{% url 'assets:consumable_list' %}?quick_search=low_stock"><i
                                        class="fas fa-exclamation-triangle me-2"></i>低库存耗材</a></li>
                        </ul>
                    </li>
                    -->
                    <li class="nav-item dropdown">
                        <a class="nav-link dropdown-toggle" href="#" id="reportManagementDropdown" role="button"
                            data-bs-toggle="dropdown">
                            <i class="fas fa-chart-line"></i> 报表管理
                        </a>
                        <ul class="dropdown-menu dropdown-menu-center">
                            <!-- 基础报表 -->
                            <li>
                                <h6 class="dropdown-header"><i class="fas fa-file-alt me-2"></i>基础报表</h6>
                            </li>
                            <li><a class="dropdown-item" href="{% url 'assets:asset_report' %}"><i
                                        class="fas fa-boxes me-2"></i>资产报表</a></li>

                            <li>
                                <hr class="dropdown-divider">
                            </li>

                            <!-- 分析仪表板 -->
                            <li>
                                <h6 class="dropdown-header"><i class="fas fa-tachometer-alt me-2"></i>数据分析</h6>
                            </li>
                            <li><a class="dropdown-item" href="{% url 'assets:analytics_dashboard' %}"><i
                                        class="fas fa-chart-pie me-2"></i>分析仪表板</a></li>
                            <li><a class="dropdown-item" href="{% url 'assets:asset_analytics' %}"><i
                                        class="fas fa-cubes me-2"></i>资产分析</a></li>
                            <li><a class="dropdown-item" href="{% url 'assets:maintenance_analytics' %}"><i
                                        class="fas fa-tools me-2"></i>维修分析</a></li>

                            <li>
                                <hr class="dropdown-divider">
                            </li>

                            <!-- 库存预警与状态 -->
                            <li>
                                <h6 class="dropdown-header"><i class="fas fa-exclamation-triangle me-2"></i>库存预警</h6>
                            </li>
                            <li><a class="dropdown-item" href="{% url 'assets:inventory_alert_dashboard' %}"><i
                                        class="fas fa-tachometer-alt me-2"></i>预警仪表板</a></li>
                            <li><a class="dropdown-item" href="{% url 'assets:inventory_alert_list' %}"><i
                                        class="fas fa-exclamation-triangle me-2"></i>预警列表</a></li>
                            <li><a class="dropdown-item" href="{% url 'assets:inventory_status_overview' %}"><i
                                        class="fas fa-chart-bar me-2"></i>库存状态</a></li>

                            <li>
                                <hr class="dropdown-divider">
                            </li>

                            <!-- 数据导出 -->
                            <li>
                                <h6 class="dropdown-header"><i class="fas fa-download me-2"></i>数据导出</h6>
                            </li>
                            <li><a class="dropdown-item" href="{% url 'assets:export_analytics_data' %}?type=assets"><i
                                        class="fas fa-file-excel me-2"></i>导出资产报表</a></li>
                            <li><a class="dropdown-item"
                                    href="{% url 'assets:export_analytics_data' %}?type=maintenance"><i
                                        class="fas fa-file-excel me-2"></i>导出维修报表</a></li>
                            <li><a class="dropdown-item"
                                    href="{% url 'assets:export_analytics_data' %}?type=inventory"><i
                                        class="fas fa-file-excel me-2"></i>导出库存报表</a></li>
                        </ul>
                    </li>
                    {% endif %}
                </ul>
                <ul class="navbar-nav ms-auto">
                    {% if user.is_authenticated %}
                    <li class="nav-item dropdown">
                        <a class="nav-link dropdown-toggle" href="#" id="profileDropdown" role="button"
                            data-bs-toggle="dropdown">
                            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor"
                                class="bi bi-person-circle" viewBox="0 0 16 16">
                                <path d="M11 6a3 3 0 1 1-6 0 3 3 0 0 1 6 0z" />
                                <path fill-rule="evenodd"
                                    d="M0 8a8 8 0 1 1 16 0A8 8 0 0 1 0 8zm8-7a7 7 0 0 0-5.468 11.37C3.242 11.226 4.805 10 8 10s4.757 1.225 5.468 2.37A7 7 0 0 0 8 1z" />
                            </svg>
                            {{ user.username }}
                        </a>
                        <ul class="dropdown-menu dropdown-menu-end">
                            <li><a class="dropdown-item" href="{% url 'assets:profile_view' %}"><i
                                        class="fas fa-user me-2"></i>个人资料</a></li>
                            <li><a class="dropdown-item" href="{% url 'assets:task_list' %}"><i
                                        class="fas fa-tasks me-2"></i>我的任务</a></li>
                            <li><a class="dropdown-item" href="{% url 'assets:change_password' %}"><i
                                        class="fas fa-key me-2"></i>修改密码</a></li>
                            <li>
                                <hr class="dropdown-divider">
                            </li>
                            <li><a class="dropdown-item" href="{% url 'assets:logout' %}"><i
                                        class="fas fa-sign-out-alt me-2"></i>退出登录</a></li>
                        </ul>
                    </li>
                    {% else %}
                    <li class="nav-item">
                        <a class="nav-link" href="{% url 'assets:login' %}">登录</a>
                    </li>
                    {% endif %}
                </ul>
            </div>
        </div>
    </nav>

    <div class="container mt-4">
        {% block content %}
        {% endblock %}
    </div>

    <!-- Iframe 模态框 -->
    <div class="modal fade" id="actionIframeModal" tabindex="-1" aria-hidden="true">
      <div class="modal-dialog modal-xl modal-dialog-scrollable">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title" id="actionIframeTitle">操作</h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="关闭"></button>
          </div>
          <div class="modal-body p-0 position-relative" style="height: 70vh;">
            <div id="iframeLoading" class="d-flex align-items-center justify-content-center w-100 h-100 position-absolute top-0 start-0 bg-light" style="z-index: 2;">
              <div class="text-center">
                <div class="spinner-border text-primary" role="status" aria-label="加载中"></div>
                <div class="mt-2 text-muted small">正在加载，请稍候…</div>
              </div>
            </div>
            <div id="iframeError" class="d-none align-items-center justify-content-center w-100 h-100 position-absolute top-0 start-0 bg-light" style="z-index: 2;">
              <div class="text-center text-muted">
                <i class="fas fa-exclamation-triangle fa-2x mb-2"></i>
                <div>页面加载失败，可能被浏览器或服务器安全策略拦截（X-Frame-Options/CSP）。</div>
                <div class="small">请联系管理员或点击下方按钮在新窗口打开。</div>
                <a id="iframeOpenNewTab" href="#" target="_blank" class="btn btn-sm btn-outline-primary mt-2">在新窗口打开</a>
              </div>
            </div>
            <iframe id="actionIframeFrame" src="about:blank" style="border:0;width:100%;height:100%; position:relative; z-index:1;"></iframe>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
            <button type="button" class="btn btn-success" id="iframeSubmitBtn" title="提交子页面中的表单并保存">
              提交并保存
            </button>
          </div>
        </div>
      </div>
    </div>

    {# 全局消息提示：使用 Bootstrap Toast 弹窗显示，而不是页面顶部横幅 #}
    {% if messages %}
    <div id="toastContainer" class="position-fixed top-0 end-0 p-3" style="z-index: 1080;"></div>
    <div id="djangoMessages" style="display:none;">
        {% for message in messages %}
        <div class="msg" data-level="{{ message.tags }}">{{ message }}</div>
        {% endfor %}
    </div>

    <!-- 全局成功提示模态框（可通过 UI_FLAGS 控制） -->
    <div class="modal fade" id="globalSuccessModal" tabindex="-1" aria-labelledby="globalSuccessModalLabel" aria-hidden="true">
      <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
          <div class="modal-header bg-success text-white">
            <h5 class="modal-title" id="globalSuccessModalLabel"><i class="fas fa-check-circle me-2"></i>操作成功</h5>
            <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
          </div>
          <div class="modal-body"><div id="globalSuccessText">操作已完成</div></div>
          <div class="modal-footer">
            <button type="button" class="btn btn-success" data-bs-dismiss="modal">知道了</button>
          </div>
        </div>
      </div>
    </div>

    <script>
        // 处理 iframe 模态框（等待 Bootstrap 可用，且可重复调用，幂等）
        function initIframeModal() {
            try {
                if (!window.bootstrap) return false;
                const modalEl = document.getElementById('actionIframeModal');
                if (!modalEl || modalEl.dataset.initialized === 'true') return !!modalEl;

                const modal = new bootstrap.Modal(modalEl);
                const iframe = document.getElementById('actionIframeFrame');
                const iframeTitle = document.getElementById('actionIframeTitle');
                const iframeLoading = document.getElementById('iframeLoading');
                const iframeError = document.getElementById('iframeError');
                const iframeOpenNewTab = document.getElementById('iframeOpenNewTab');
                const iframeSubmitBtn = document.getElementById('iframeSubmitBtn');

                // 委托点击：任何 a[data-modal="iframe"]
                document.addEventListener('click', function(e) {
                    const link = e.target.closest('a[data-modal="iframe"]');
                    if (!link) return;

                    e.preventDefault();
                    e.stopPropagation();

                    const url = link.getAttribute('href');
                    const title = link.getAttribute('data-title') || '操作';

                    // 添加 modal=1 参数
                    let finalUrl = url;
                    try {
                        const u = new URL(url, window.location.origin);
                        u.searchParams.set('modal', '1');
                        finalUrl = u.toString();
                    } catch (err) {
                        finalUrl = url + (url.includes('?') ? '&' : '?') + 'modal=1';
                    }

                    // 先通过 HEAD 请求判断是否为 PDF，PDF 则走模态框预览，非 PDF 则直接下载（新标签）
                    if (iframeLoading) iframeLoading.classList.remove('d-none');
                    if (iframeError) iframeError.classList.add('d-none');
                    if (iframeTitle) iframeTitle.textContent = title;
                    iframe.style.visibility = 'hidden';

                    // 默认操作：若检测失败，则回退为在当前窗口打开（让服务器决定下载/预览）
                    const fallbackOpen = function() {
                        try {
                            // 使用新窗口避免打断当前页面
                            const a = document.createElement('a');
                            a.href = finalUrl;
                            a.target = '_blank';
                            a.rel = 'noopener';
                            document.body.appendChild(a);
                            a.click();
                            a.remove();
                        } catch (e) {
                            // 最后兜底
                            window.location.href = finalUrl;
                        }
                    };

                    fetch(finalUrl, { method: 'HEAD', credentials: 'same-origin' })
                      .then(function(resp) {
                          const ct = (resp.headers.get('Content-Type') || '').toLowerCase();
                          const cd = (resp.headers.get('Content-Disposition') || '').toLowerCase();
                          const isPdf = ct.includes('application/pdf') || (!ct && cd.includes('inline') && cd.includes('.pdf'));
                          if (isPdf) {
                              // 设置 iframe 并显示模态框
                              iframe.src = finalUrl;
                              if (iframeOpenNewTab) iframeOpenNewTab.href = finalUrl;
                              modal.show();

                              // 监听 iframe 加载完成
                              iframe.onload = function() {
                                  if (iframeLoading) iframeLoading.classList.add('d-none');
                                  iframe.style.visibility = 'visible';
                                  try {
                                      if (iframe.contentWindow.location.href === 'about:blank') return;
                                  } catch (err) {
                                      if (iframeError) iframeError.classList.remove('d-none');
                                      return;
                                  }
                              };

                              // 监听 iframe 加载错误
                              iframe.onerror = function() {
                                  if (iframeLoading) iframeLoading.classList.add('d-none');
                                  if (iframeError) iframeError.classList.remove('d-none');
                              };
                          } else {
                              // 非 PDF：下载/在新窗口打开
                              if (iframeLoading) iframeLoading.classList.add('d-none');
                              fallbackOpen();
                          }
                      })
                      .catch(function(err) {
                          console.warn('HEAD 检测失败，使用回退行为:', err);
                          if (iframeLoading) iframeLoading.classList.add('d-none');
                          fallbackOpen();
                      });
                }, true);

                // 提交按钮
                if (iframeSubmitBtn) {
                    iframeSubmitBtn.addEventListener('click', function() {
                        try {
                            const iframeForm = iframe.contentDocument && iframe.contentDocument.querySelector('form');
                            if (iframeForm) {
                                iframeForm.submit();
                            } else {
                                alert('未找到可提交的表单');
                            }
                        } catch (err) {
                            console.error('提交表单时出错:', err);
                            alert('提交表单时出错: ' + err.message);
                        }
                    });
                }

                // 模态框关闭时清空 iframe
                modalEl.addEventListener('hidden.bs.modal', function() {
                    iframe.src = 'about:blank';
                });

                // 标记已初始化
                modalEl.dataset.initialized = 'true';
                return true;
            } catch (e) {
                console.error('initIframeModal error:', e);
                return false;
            }
        }

        // DOM 就绪也尝试一次（若此时 Bootstrap 已可用）
        document.addEventListener('DOMContentLoaded', function() { initIframeModal(); });

        // 等页面与Bootstrap加载完成后再显示Toast/Modal
        window.addEventListener('load', function () {
            // 初始化 iframe 模态框
            initIframeModal();
            const flags = (window.UI_FLAGS || {});
            const start = Date.now();
            const run = function(){
            const levelToHeaderClass = {
                success: 'bg-success text-white',
                warning: 'bg-warning text-dark',
                error:   'bg-danger text-white',
                danger:  'bg-danger text-white',
                info:    'bg-info text-dark'
            };
            const levelToIcon = {
                success: '<i class="fas fa-check-circle me-2"></i>',
                warning: '<i class="fas fa-exclamation-triangle me-2"></i>',
                error:   '<i class="fas fa-times-circle me-2"></i>',
                danger:  '<i class="fas fa-times-circle me-2"></i>',
                info:    '<i class="fas fa-info-circle me-2"></i>'
            };
            const levelToDelay = {
                success: 2500,
                info:    3000,
                warning: 4000,
                error:   6000,
                danger:  6000
            };

            const container = document.getElementById('toastContainer');
            const holder = document.getElementById('djangoMessages');
            if (!holder) return;

            // Toast 居中控制
            if (container && (flags.toastCenter !== false)) {
                container.classList.add('center-top');
            }

            const msgs = Array.from(holder.querySelectorAll('.msg')).map(n => ({
                level: n.getAttribute('data-level') || 'info',
                text: n.textContent
            }));

            // 渲染所有消息为Toast
            msgs.forEach(m => {
                const toast = document.createElement('div');
                toast.className = 'toast align-items-center border-0 shadow';
                toast.setAttribute('role', 'alert');
                toast.setAttribute('aria-live', 'assertive');
                toast.setAttribute('aria-atomic', 'true');
                toast.style.minWidth = '320px';
                const headerClass = levelToHeaderClass[m.level] || 'bg-primary text-white';
                const iconHtml = levelToIcon[m.level] || '<i class="fas fa-bell me-2"></i>';
                toast.innerHTML = `
                    <div class="toast-header ${headerClass}">
                        <span class="me-auto d-flex align-items-center">${iconHtml}<strong>提示</strong></span>
                        <small class="text-white-50">现在</small>
                        <button type="button" class="btn-close btn-close-white ms-2 mb-1" data-bs-dismiss="toast" aria-label="Close"></button>
                    </div>
                    <div class="toast-body"></div>
                `;
                toast.querySelector('.toast-body').textContent = m.text;
                container.appendChild(toast);
                const delay = levelToDelay[m.level] || 3000;
                const t = new bootstrap.Toast(toast, { delay, autohide: true });
                t.show();
            });

            // 成功模态框（可选）
            if ((flags.successModalOnSuccess !== false)) {
                const successTexts = msgs.filter(m => m.level === 'success').map(m => m.text);
                if (successTexts.length > 0) {
                    const text = successTexts.join('\n');
                    const body = document.getElementById('globalSuccessText');
                    if (body) body.textContent = text || '操作已完成';
                    const modalEl = document.getElementById('globalSuccessModal');
                    if (modalEl) {
                        const m = new bootstrap.Modal(modalEl, { backdrop: 'static' });
                        m.show();
                        // 友好自动关闭（用户也可手动关闭）
                        setTimeout(() => { try { m.hide(); } catch (e) {} }, 2200);
                    }
                }
            }
            };
            // 等待 Bootstrap 可用
            const wait = function(){
              if (window.bootstrap && window.bootstrap.Toast && window.bootstrap.Modal) { run(); return; }
              if (Date.now() - start > 10000) { console.error('Bootstrap not ready for messages'); return; }
              setTimeout(wait, 50);
            };
            wait();
        });
    </script>
    {% endif %}

    <div class="footer">
        <div class="container">
            <p>&copy; 2025 固定资产管理系统. 技术部·运维保障科.</p>

        </div>
    </div>

    <!-- 全局二次确认通用模态框 -->
    <div class="modal fade" id="globalConfirmModal" tabindex="-1" aria-labelledby="globalConfirmModalLabel" aria-hidden="true">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title" id="globalConfirmModalLabel">请确认</h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
          </div>
          <div class="modal-body" id="globalConfirmText">确定要执行此操作吗？</div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
            <button type="button" class="btn btn-danger" id="globalConfirmOkBtn">确认</button>
          </div>
        </div>
      </div>
    </div>

    <script>
      document.addEventListener('DOMContentLoaded', function () {
        // 1) 启用所有带有 data-bs-toggle="tooltip" 的提示（等待 Bootstrap 可用）
        (function waitBootstrapForTooltips(){
          if (window.bootstrap && window.bootstrap.Tooltip) {
            try {
              const tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
              tooltipTriggerList.forEach(function (tooltipTriggerEl) {
                new bootstrap.Tooltip(tooltipTriggerEl);
              });
            } catch(e) { console.warn('Init tooltip failed:', e); }
          } else {
            setTimeout(waitBootstrapForTooltips, 50);
          }
        })();

        // 2) 防重复提交：禁用提交按钮并显示加载态
        document.querySelectorAll('form').forEach(function (form) {
          form.addEventListener('submit', function (e) {
            if (form.dataset.submitting === 'true') {
              e.preventDefault();
              e.stopPropagation();
              return false;
            }
            form.dataset.submitting = 'true';
            // 禁用所有提交按钮
            form.querySelectorAll('button[type="submit"], input[type="submit"]').forEach(function (btn) {
              btn.disabled = true;
              if (!btn.dataset.originalHtml) {
                btn.dataset.originalHtml = btn.innerHTML;
              }
              // 增加加载中指示
              if (!btn.classList.contains('btn-loading')) {
                btn.classList.add('btn-loading');
                btn.innerHTML = '<span class="spinner-border spinner-border-sm me-2" role="status" aria-hidden="true"></span>' + (btn.dataset.loadingText || btn.textContent.trim() || '提交中...');
              }
            });
          });
        });

        // 3) 通用确认模态框：用于任何带 data-confirm 的元素
        (function initGlobalConfirm() {
          const confirmModalEl = document.getElementById('globalConfirmModal');
          const confirmTextEl = document.getElementById('globalConfirmText');
          const confirmOkBtn = document.getElementById('globalConfirmOkBtn');
          if (!confirmModalEl || !confirmTextEl || !confirmOkBtn) return;
          const confirmModal = new bootstrap.Modal(confirmModalEl);
          let pendingAction = null;

          document.body.addEventListener('click', function (e) {
            const el = e.target.closest('[data-confirm]');
            if (!el) return;
            // 只对未标记跳过的元素处理
            if (el.dataset.confirmBound === 'true') return;
            e.preventDefault();
            e.stopPropagation();

            const msg = el.getAttribute('data-confirm') || '确定要执行此操作吗？';
            confirmTextEl.textContent = msg;

            // 定义确认后的动作
            pendingAction = function () {
              // 优先考虑表单提交
              const form = el.closest('form');
              if (el.tagName === 'BUTTON' && (el.type === 'submit' || el.getAttribute('type') === 'submit') && form) {
                form.submit();
                return;
              }
              // data-submit-form 指向某个选择器
              const targetFormSel = el.getAttribute('data-submit-form');
              if (targetFormSel) {
                const tf = document.querySelector(targetFormSel);
                if (tf) { tf.submit(); return; }
              }
              // data-post-url: 以 AJAX POST 执行动作（适用于返回 JSON 的接口）
              const postUrl = el.getAttribute('data-post-url');
              if (postUrl) {
                // 兼容：优先从隐藏字段取 CSRF；若不存在则从 cookie 中获取
                const getCsrfToken = function(){
                  const tokenEl = document.querySelector('[name=csrfmiddlewaretoken]');
                  if (tokenEl && tokenEl.value) return tokenEl.value;
                  const m = document.cookie.match(/(^|;\s*)csrftoken=([^;]+)/);
                  return m ? decodeURIComponent(m[2]) : '';
                };
                const csrf = getCsrfToken();
                fetch(postUrl, {
                  method: 'POST',
                  headers: {
                    'X-CSRFToken': csrf,
                    'Content-Type': 'application/json'
                  }
                })
                .then(resp => {
                  // 优先尝试解析 JSON；若失败，仍视为成功并刷新
                  return resp.json().catch(() => ({}));
                })
                .then(data => {
                  if (!data || data.success) {
                    window.location.reload();
                  } else {
                    alert('操作失败: ' + (data.error || '未知错误'));
                  }
                })
                .catch(err => {
                  console.error('Confirm action error:', err);
                  alert('操作失败，请重试');
                });
                return;
              }
              // 链接跳转
              const href = el.getAttribute('href');
              if (href) { window.location.href = href; return; }
              // data-action-url 明确动作URL
              const actionUrl = el.getAttribute('data-action-url');
              if (actionUrl) { window.location.href = actionUrl; return; }
            };

            confirmModal.show();
          }, true);

          confirmOkBtn.addEventListener('click', function () {
            if (pendingAction) pendingAction();
            confirmModal.hide();
          });
        })();

        // 4) 自动包裹表格为响应式
        document.querySelectorAll('table.table').forEach(function (tbl) {
          // 已经被包裹则跳过
          if (tbl.parentElement && tbl.parentElement.classList.contains('table-responsive')) return;
          const wrapper = document.createElement('div');
          wrapper.className = 'table-responsive';
          tbl.parentNode.insertBefore(wrapper, tbl);
          wrapper.appendChild(tbl);
        });
      });
    </script>

    <!-- 移除重复加载：Bootstrap 与 jQuery 的 CDN 直引，改由下方动态加载器统一处理 -->

    <!-- 下拉菜单优化脚本 - 最小化版本 -->
    <script>
        // 只添加ESC键支持，其他完全交给Bootstrap处理
        document.addEventListener('keydown', function (e) {
            if (e.key === 'Escape') {
                // 简单关闭所有显示的下拉菜单
                document.querySelectorAll('.dropdown-menu.show').forEach(menu => {
                    menu.classList.remove('show');
                });
            }
        });
    </script>

    <!-- PWA安装提示 -->
    <div id="pwaInstallPrompt" class="alert alert-info alert-dismissible fade show position-fixed"
        style="top: 20px; right: 20px; z-index: 9999; display: none;" role="alert">
        <i class="fas fa-mobile-alt"></i>
        <strong>安装应用</strong><br>
        将此应用添加到主屏幕以获得更好的体验
        <button type="button" class="btn btn-sm btn-primary ms-2" id="installPwaBtn">安装</button>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>

    <!-- Service Worker 注册 -->
    <script>
        // 注册 Service Worker
        if ('serviceWorker' in navigator) {
            window.addEventListener('load', function () {
                navigator.serviceWorker.register('/static/sw.js')
                    .then(function (registration) {
                        console.log('Service Worker 注册成功:', registration.scope);

                        // 检查更新
                        registration.addEventListener('updatefound', function () {
                            const newWorker = registration.installing;
                            newWorker.addEventListener('statechange', function () {
                                if (newWorker.state === 'installed' && navigator.serviceWorker.controller) {
                                    // 有新版本可用
                                    showUpdateAvailable();
                                }
                            });
                        });
                    })
                    .catch(function (error) {
                        console.log('Service Worker 注册失败:', error);
                    });
            });
        }

        // PWA 安装提示
        let deferredPrompt;

        window.addEventListener('beforeinstallprompt', function (e) {
            // 阻止默认的安装提示
            e.preventDefault();
            deferredPrompt = e;

            // 显示自定义安装提示
            document.getElementById('pwaInstallPrompt').style.display = 'block';
        });

        // 安装按钮点击事件
        document.getElementById('installPwaBtn').addEventListener('click', function () {
            if (deferredPrompt) {
                deferredPrompt.prompt();
                deferredPrompt.userChoice.then(function (choiceResult) {
                    if (choiceResult.outcome === 'accepted') {
                        console.log('用户接受了安装提示');
                    } else {
                        console.log('用户拒绝了安装提示');
                    }
                    deferredPrompt = null;
                    document.getElementById('pwaInstallPrompt').style.display = 'none';
                });
            }
        });

        // 检测是否已安装为PWA
        window.addEventListener('appinstalled', function (evt) {
            console.log('PWA 已安装');
            document.getElementById('pwaInstallPrompt').style.display = 'none';
        });

        // 显示更新可用提示
        function showUpdateAvailable() {
            const updateAlert = `
                <div class="alert alert-warning alert-dismissible fade show position-fixed" style="top: 80px; right: 20px; z-index: 9999;" role="alert">
                    <i class="fas fa-sync-alt"></i> 
                    <strong>更新可用</strong><br>
                    有新版本可用，请刷新页面获取最新功能
                    <button type="button" class="btn btn-sm btn-warning ms-2" onclick="location.reload()">刷新</button>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            `;
            document.body.insertAdjacentHTML('beforeend', updateAlert);
        }

        // 网络状态检测
        function updateOnlineStatus() {
            const status = navigator.onLine ? 'online' : 'offline';

            if (status === 'offline') {
                showOfflineNotification();
            } else {
                hideOfflineNotification();
            }
        }

        function showOfflineNotification() {
            if (!document.getElementById('offlineNotification')) {
                const offlineAlert = `
                    <div id="offlineNotification" class="alert alert-warning position-fixed w-100" style="top: 0; left: 0; z-index: 10000; border-radius: 0; margin: 0;">
                        <div class="container text-center">
                            <i class="fas fa-wifi"></i> 
                            您当前处于离线状态，某些功能可能不可用
                        </div>
                    </div>
                `;
                document.body.insertAdjacentHTML('afterbegin', offlineAlert);

                // 调整页面内容位置
                document.body.style.paddingTop = '60px';
            }
        }

        function hideOfflineNotification() {
            const notification = document.getElementById('offlineNotification');
            if (notification) {
                notification.remove();
                document.body.style.paddingTop = '0';
            }
        }

        // 监听网络状态变化
        window.addEventListener('online', updateOnlineStatus);
        window.addEventListener('offline', updateOnlineStatus);

        // 初始化网络状态
        updateOnlineStatus();
    </script>

    <!-- jQuery with local fallback -->
    <script>
    (function() {
        var jqueryLoaded = false;
        var loadJQuery = function() {
            if (jqueryLoaded) return;
            jqueryLoaded = true;
            
            // Try CDN first
            var script = document.createElement('script');
            script.src = 'https://code.jquery.com/jquery-3.6.0.min.js';
            script.integrity = 'sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=';
            script.crossOrigin = 'anonymous';
            
            script.onload = function() {
                console.log('jQuery loaded from CDN');
                loadBootstrap();
            };
            
            script.onerror = function() {
                console.log('Failed to load jQuery from CDN, trying local');
                var localScript = document.createElement('script');
                localScript.src = '{% static "vendor/jquery/jquery-3.6.0.min.js" %}';
                localScript.onload = function() {
                    console.log('jQuery loaded from local');
                    loadBootstrap();
                };
                localScript.onerror = function() {
                    console.error('Failed to load jQuery from local');
                };
                document.body.appendChild(localScript);
            };
            
            document.body.appendChild(script);
        };
        
        // Bootstrap loader
        var bootstrapLoaded = false;
        var loadBootstrap = function() {
            if (bootstrapLoaded) return;
            bootstrapLoaded = true;
            
            var script = document.createElement('script');
            script.src = '{% static "vendor/bootstrap/bootstrap.bundle.min.js" %}';
            
            script.onload = function() {
                // 本地文件可能为空或损坏（0 字节），这里校验是否真正挂载了 window.bootstrap
                if (window.bootstrap && (window.bootstrap.Modal || window.bootstrap.Toast || window.bootstrap.Tooltip)) {
                    if (window.UI_DEBUG === true) { console.debug('Bootstrap loaded from local'); }
                    initBootstrap();
                } else {
                    console.warn('Local Bootstrap bundle seems invalid, trying CDN');
                    var cdnScript = document.createElement('script');
                    cdnScript.src = 'https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js';
                    cdnScript.onload = function(){
                        if (window.bootstrap) {
                            if (window.UI_DEBUG === true) { console.debug('Bootstrap loaded from CDN (fallback after invalid local)'); }
                            initBootstrap();
                        } else {
                            console.error('Bootstrap not available even after CDN fallback');
                        }
                    };
                    cdnScript.onerror = function(){
                        console.error('Failed to load Bootstrap from CDN (after invalid local)');
                    };
                    document.body.appendChild(cdnScript);
                }
            };
            
            script.onerror = function() {
                console.warn('Failed to load Bootstrap from local, trying CDN');
                var cdnScript = document.createElement('script');
                cdnScript.src = 'https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js';
                cdnScript.onload = function() {
                    if (window.UI_DEBUG === true) { console.debug('Bootstrap loaded from CDN'); }
                    initBootstrap();
                };
                cdnScript.onerror = function() {
                    console.error('Failed to load Bootstrap from CDN');
                };
                document.body.appendChild(cdnScript);
            };
            
            document.body.appendChild(script);
        };
        
        // 立刻尝试加载 Bootstrap（不要等待 DOMContentLoaded 或 jQuery），
        // 以确保页面内可能早于 DOM 就绪执行的脚本也能拿到 window.bootstrap。
        try { loadBootstrap(); } catch (e) { console.warn('Auto loadBootstrap failed:', e); }
        
        // Initialize Bootstrap components
        var initBootstrap = function() {
            console.log('Initializing Bootstrap components');
            // Tooltip initialization
            var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
            tooltipTriggerList.map(function (tooltipTriggerEl) {
                return new bootstrap.Tooltip(tooltipTriggerEl);
            });
            
            // Popover initialization
            var popoverTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="popover"]'));
            popoverTriggerList.map(function (popoverTriggerEl) {
                return new bootstrap.Popover(popoverTriggerEl);
            });
        };
        
        // Start loading jQuery when DOM is ready
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', loadJQuery);
        } else {
            loadJQuery();
        }
    })();
    </script>
    
    {% block extra_js %}{% endblock %}
    
    <script>
    // Debug: Check if required libraries are loaded
    document.addEventListener('DOMContentLoaded', function() {
        console.log('jQuery loaded:', !!window.jQuery);
        console.log('Bootstrap loaded:', !!window.bootstrap);
    });
    </script>
</body>

</html>